package seis635.ui;

import seis635.design.*;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import java.text.DateFormat;

public class StopwatchUI{

	private DateFormat timerFormat = MainUI.getTimerFormat();
	private Stopwatch sw;
	private JButton swMainButton;
	private JButton swRecordButton;
	private JButton swClearButton;
	boolean isStartButton = true;
	private JLabel swTimeLabel;
	private JTextArea swTextArea;
	private JScrollPane swscrollPanel;
	private int i = 1;
	private JButton swPauseButton;
	private JPanel swPanel;

	public JPanel getSWPanel(){
		return swPanel;
	}
	public StopwatchUI(Stopwatch s){
		timerFormat.setTimeZone(TimeZone.getTimeZone("GTM+0"));
		this.sw = s;

		swMainButton = new JButton("Start");
		swRecordButton = new JButton("Record");
		swRecordButton.setEnabled(false);
		swClearButton = new JButton("Clear");
		swPauseButton = new JButton("Pause");
		swPauseButton.setEnabled(false);

		swTextArea = new JTextArea(10,30);
		swTextArea.setEditable(false);
		swTextArea.setLineWrap(true);
		swscrollPanel = new JScrollPane (swTextArea);
		swscrollPanel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		swTimeLabel = new JLabel(timerFormat.format(new java.util.Date(0)));
		
		swPanel = new JPanel();
		swPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		swPanel.add(swTimeLabel);
		swPanel.add(swMainButton);
		swPanel.add(swClearButton);
		swPanel.add(swPauseButton);
		swPanel.add(swRecordButton);
		swPanel.add(swscrollPanel);

		
		swPauseButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				sw.pause();
				swPauseButton.setEnabled(false);
				isStartButton = true;
				swMainButton.setText("Resume");
			}
		});

		swMainButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				if (isStartButton==true){
					swMainButton.setText("Stop");
					sw.start();
					isStartButton=false;
					swPauseButton.setEnabled(true);
				}
				else{
					swMainButton.setText("Start");
					sw.stop();
					isStartButton = true;
				}				
			}
		});

		swRecordButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				sw.record();
			}
		});

		swClearButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				swTextArea.setText("");
				i = 1;
			}
		});	
	}

	public void updateSWLabel(long time){
		this.swTimeLabel.setText(timerFormat.format(new java.util.Date(time)));
	}
	public void updateSWTextArea(long time){
		String old  = this.swTextArea.getText();
		this.swTextArea.setText(old + "\n" + "Record " 
				+ i + ": " + timerFormat.format(new java.util.Date(time)));
		i++;
	}
	public void swRecordButtonState(boolean state){
		swRecordButton.setEnabled(state);
	}
	public void swPauseButtonState(boolean state){
		swPauseButton.setEnabled(state);
	}
}